#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "log.h"
#include "tracelog.h"
#include "db_log.h"
//mss specific
#include <sqlfront.h>
#include <sqldb.h>	   // DB-LIB header file (should always be included)

//------------------------------------------------------------------------
//------------------------- MSS ------------------------------------------
//------------------------------------------------------------------------

typedef DBMSGHANDLE_PROC (SQLAPI *__dbmsghandle_proc)(DBMSGHANDLE_PROC);


HINSTANCE		 _mss_lib=NULL;
__dbmsghandle_proc _mss_dberrhandleproc=NULL;
DBMSGHANDLE_PROC _old_dbmsghandle=NULL;

INT SQLAPI _new_dbmsghandle(PDBPROCESS c, DBINT msgno, INT msgstate, INT severity, LPCSTR msgtext, LPCSTR srvname, LPCSTR procname, DBUSMALLINT line){
	_db_message_handler((severity==0||severity==10)?false:true,msgno,msgtext,procname,line);
	if(_old_dbmsghandle)return _old_dbmsghandle( c, msgno, msgstate, severity, msgtext, srvname, procname, line);
	return 0;
}

bool _load_mss(){
	if(!_mss_lib)_mss_lib=LoadLibrary(L"ntwdblib.dll");
	if(!_mss_lib){
		tracelog_add(1, L"tracelog.dll", L"Can't load MSS client library ntwdblib.dll.");
		return false;
	}
	if(!_mss_dberrhandleproc)_mss_dberrhandleproc=(__dbmsghandle_proc)GetProcAddress(_mss_lib,"dbmsghandle");
	if(!_mss_dberrhandleproc){
		tracelog_add(1, L"tracelog.dll", L"Can't find \"dbmsghandle\" function in ntwdblib.dll.");
		return false;
	}
	return true;
}


bool install_message_callback_mss( void * _con ){
	if(!_load_mss())return false;
	if(_old_dbmsghandle){
		tracelog_add(1, L"tracelog.dll", L"Should remove message handler before reinstalling it.");
		return false;
	}
	_old_dbmsghandle = _mss_dberrhandleproc (_new_dbmsghandle);
	return true;
}

bool remove_message_callback_mss( void * _con ){
	if(!_load_mss())return false;
	_mss_dberrhandleproc (_old_dbmsghandle);
	_old_dbmsghandle = NULL;
	return true;
}


